﻿using System;
using System.Diagnostics;
using Microsoft.SharePoint;

namespace RH.PictureLibraryExif
{
    public class FeatureReceiver : SPFeatureReceiver
    {
        private string assembly = "MetaPic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce54f2f07031df02";
        private string receiver = "MetaPic.PictureItemEventReceiver";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb site = (SPWeb)properties.Feature.Parent;

                // look for any picture library in the site
                for (int i = 0; i < site.Lists.Count; i++)
                {
                    if (site.Lists[i].BaseTemplate == SPListTemplateType.PictureLibrary)
                    {
                        // add the event receiver to wath for new images
                        site.Lists[i].EventReceivers.Add(
                            SPEventReceiverType.ItemAdded,
                            assembly,
                            receiver);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw;
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                var site = (SPWeb)properties.Feature.Parent;

                // look for any picture library in the site
                for (int i = 0; i < site.Lists.Count; i++)
                {
                    if (site.Lists[i].BaseTemplate != SPListTemplateType.PictureLibrary)
                    {
                        return;
                    }

                    // find and remove the event handler
                    foreach (SPEventReceiverDefinition receiver in site.Lists[i].EventReceivers)
                    {
                        if (receiver.Type == SPEventReceiverType.ItemAdded)
                        {
                            receiver.Delete();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw;
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
